package jafou.client.ui.objects;

import jafou.client.remote.JafouService;
import jafou.client.remote.JafouServiceAsync;
import jafou.client.ui.ForumWidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.TextBox;

public class NewPostPanel extends PopupPanel {
	private ForumWidget ui;
	private RichTextArea postArea;
	private Button button;
	private String topicId;
	
	private final JafouServiceAsync handler = GWT.create(JafouService.class);

	public NewPostPanel(ForumWidget ui, String topicId) {
		super(false, true);
		this.ui = ui;
		this.topicId = topicId;
		render();
	}
	
	private AsyncCallback<String> postCallback = new AsyncCallback<String> () {

		@Override
		public void onFailure(Throwable caught) {
			handleCreateOnFailure(caught);
		}

		@Override
		public void onSuccess(String result) {
			handleCreateOnSuccess(result);
		}
		
	};

	private ClickHandler postHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			String html = postArea.getHTML();
			if (html == null || "".equals(html)) {
				Window.alert("post must not be empty.");
			} else {
				button.setVisible(false);
				handler.addPost(html, topicId, postCallback);
			}
		}
	};
	
	private ClickHandler cancelHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			ui.handlePostCreation(false, "", "");
		}
	};
	
	private void render() {
		FlowPanel main = new FlowPanel();
		main.addStyleName("main-panel");
		main.add(new Label("posting message "));
		postArea = new RichTextArea();
		postArea.addStyleName("main-panel");
		main.add(postArea);
		HorizontalPanel buttonPanel = new HorizontalPanel();
		main.add(buttonPanel);
		button = new Button("post", postHandler);
		buttonPanel.add(button);
		buttonPanel.add(new Button("cancel", cancelHandler));
		add(main);
		setSize("80%", "80%");
	}
	
	private void handleCreateOnSuccess(String id) {
		ui.handlePostCreation(true, id, topicId);
	}
	
	private void handleCreateOnFailure(Throwable caught) {
		ui.handlePostCreation(false, "", "");
	}

}
